import { taskType } from "../../../enum"
import { creepNameToObj, objIDToObj } from "../../../tools/baseTools"
import { changeCreepRule, changeCreepRuleBytask, creepGetSource, creepGetTask, creepMoveExtesion } from "../../../tools/tools/creepTool"
import taskManager from "../../task/taskManager"

export default {
    run: function (creep) {
        // 任务池
        let taskPool = [taskType.repaire]
        creep = creepNameToObj(creep)
        if (!creep.memory.currentTaskID) changeCreepRule(creep) // 每一个creep都需要存在一个无currentTaskID的情况
        if (creep.memory.state.isWorking) {
            // 工作逻辑
            ruleRepaireWorking(creep)
        }
        else {
            // 准备逻辑
            creepGetSource({ creep: creep, room: creep.room, sourceType: creep.memory.params.resouce })
        }
    }
}

function ruleRepaireWorking(creep) {
    creep = creepNameToObj(creep)
    let targetObj = objIDToObj(creep.memory.targetID[creep.memory.targetID.length - 1])
    if (!targetObj) {
        taskManager.finishTask(creep.memory.currentTaskID, creep.memory.targetPos.roomName, { obj: creep })
        changeCreepRule(creep)
        return
    }
    let result = false
    let resultCode = creep.repair(targetObj)
    // console.log(`builder的逻辑结果编码${resultCode}`);
    switch (resultCode) {
        case OK:
            if (creep.memory.state.isRuning) {
                creep.memory.state.isRuning = false
                creep.memory.state.isBlock = false
                creep.memory.state.sleep = false
            }
            if (targetObj.hits == targetObj.hitsMax) {
                taskManager.finishTask(creep.memory.currentTaskID, creep.memory.targetPos.roomName, { obj: creep })
                let resultDate = taskManager.getTaskByType(taskType.repaire, creep, creep.pos.roomName, false)
                // console.log('完成任务后参数情况' + JSON.stringify(resultDate));
                if (resultDate.count == 0) {
                    changeCreepRule(creep)
                    break
                } else {
                    let taskDeta = taskManager.getTaskByID(resultDate.taskID, creep.name, creep.pos.roomName, true)
                    if (!taskDeta) {
                        changeCreepRule(creep)
                        break
                    }
                    creep.memory.currentTaskID = resultDate.taskID
                    creep.memory.targetID = [taskDeta.publisherID]
                }
            }
            result = true
            break;
        case ERR_NOT_IN_RANGE:
            creepMoveExtesion(creep)
            break;
        case ERR_NOT_ENOUGH_RESOURCES:
            creep.memory.state.isRuning = false
            creep.memory.state.isWorking = false
            break;
        default:
            creep.memory.state.isRuning = false
            console.log(creep.name + `使用repair的逻辑可能出现问题了,错误编码${resultCode}`);
            break;
    }
    return result
}